<?php

class Kd_Html_Form_CheckList extends Kd_Html_Form_Element {
	
    private $_options = array();
	private $_groupable = FALSE;
	
    public function  __construct() {
        parent::__construct();
        $this->templateName = 'form/checklist';
        $this->addClass('checkbox-list');
    }
    
    public function getGroupable(){
    	return $this->_groupable;
    }
    
    public function setGroupable($value){
    	$this->_groupable = $value;
    	return $this;
    }

    public function setOption($label, $value, $group = NULL){
    	if($this->getGroupable()){
    		if(!array_key_exists($group, $this->_options)){
    			$this->_options[$group] = array();
    		}
    		$this->_options[$group][] = array('label'=>$label, 'value'=>$value);
    	}else{
        $this->_options[] = array('label'=>$label, 'value'=>$value);
    	}
        return $this;
    }
    
    public function bindData($data, $labelKey, $valueKey, $groupKey = NULL){
        foreach($data as $item){
            $this->setOption($item[$labelKey], $item[$valueKey], $item[$groupKey]);
        }
        return $this;
    }

    protected function renderReadonly(){
        $this->setEnabled(FALSE)
             ->addClass('readonly');
        return $this->renderEditable();
    }

    protected function renderEditable(){
        $result = '';
        $selectedValues = is_array($this->getValue())? $this->getValue(): array($this->getValue());
        if($this->getGroupable()){
        	$result .= '<div'.$this->getAttributeHtml().'>';
        	foreach($this->_options as $group=>$items){
				$result .= '<div class="group">'.$group;
	        	$result .= '<ul>';
		        foreach($items as $item){
		            $result .= $this->createOptionHtml($selectedValues, $item['label'], $item['value']);
		        }
		        $result .= '</ul></div>';        		
        	}
        	$result .= '</div>';
        }else{
        	$result .= '<ul'.$this->getAttributeHtml().'>';
	        foreach($this->_options as $item){
	            $result .= $this->createOptionHtml($selectedValues, $item['label'], $item['value']);
	        }
	        $result .= '</ul>';
        }
        return $result;
    }

    private function createOptionHtml($selectedValues, $label, $value){
    	$selected = '';
    	if(!empty($selectedValues)){
        	$selected = in_array($value, $selectedValues)? ' checked="checked"': '';
    	}
        return sprintf('<li><input type="checkbox" name="%s" value="%s"%s><span>%s</span></li>', $this->getName(), $value, $selected, $label);
    }
}